/*
 * ServiceLocator.java
 *
 * Created on 12 2007 20:54
 */
package server.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.Collections;
import java.net.URL;

import javax.ejb.EJBHome;
import javax.ejb.EJBLocalHome;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.TopicConnectionFactory;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.sql.DataSource;
import javax.mail.Session;

/**
 *
 * @author alexog
 * @version
 */
public class ServiceLocator {
    
    private InitialContext ic;
    private Map cache;
    
    private static ServiceLocator me;
    
    static {
        try {
            me = new ServiceLocator();
        } catch(NamingException se) {
            throw new RuntimeException(se);
        }
    }
    
    private ServiceLocator() throws NamingException  {
        ic = new InitialContext();
        cache = Collections.synchronizedMap(new HashMap());
    }
    
    public static ServiceLocator getInstance() {
        return me;
    }
    
    private Object lookup(String jndiName) throws NamingException {
        Object cachedObj = cache.get(jndiName);
        if (cachedObj == null) {
            cachedObj = ic.lookup(jndiName);
            cache.put(jndiName, cachedObj);
        }
        return cachedObj;
    }
    
    /**
     * This method obtaining the topic factory
     * @return the factory for the factory to get topic connections from
     */
    public ConnectionFactory getConnectionFactory(String connFactoryName) throws NamingException {
        return (ConnectionFactory) lookup(connFactoryName);
    }
    
    /**
     * This method obtains the topic
     * @return the Topic Destination to send messages to
     */
    public Destination getDestination(String destName) throws NamingException {
        return (Destination) lookup(destName);
    }
    
     /**
     * This method obtains the ChatTopic
     * @return the Topic Destination to send messages to
     */
    public TopicConnectionFactory getTopicConnectionFactory(String connFactoryName) throws  NamingException {
        return (TopicConnectionFactory) lookup(connFactoryName);
    }
}

